#include"touch.h"
#include"lcd.h"
#include"bmp.h"
#include"video.h"
#include"music.h"
#include"dir.h"
int status_mus = 1;
// 开始播放
void start_madplay(char *str)
{
	char cmd[256] = {0};
	
	printf("madplay %s &\n", str);	// 打印拼接内容
	sprintf(cmd, "madplay %s &", str);	// 拼接新的音乐文件名
	printf("cmd: %s\n", cmd);
	
	system(cmd);	// & 后台进程
}

// 暂停播放
void stop_madplay(void)
{
	system("killall -SIGSTOP madplay");	//停止madplay进程
}

// 继续播放
void continue_madplay(void)
{
	system("killall -SIGCONT madplay");	//继续madplay进程
}


// 杀死播放
void kill_madplay(void)
{
	system("killall -SIGKILL madplay");	//杀死madplay进程
}


void music(LCD *lcd,TouchScreen *ts)
{
	/* char music_file[MUSIC_NUM][256] = {"music/1.mp3", "music/2.mp3", "music/3.mp3", "music/4.mp3" }; */
    char (*music_file)[256] = (char (*)[])calloc(100,256);
    if (music_file == NULL)
    {
        perror("music_file calloc failed");
        exit(1);
    }
    int count = 0;
    count = retrieve_file("./music",music_file,".mp3",100);
	Coordinate coor;
    anybmp(0,0,"res/madplayer.bmp",lcd);
	kill_madplay();
	int index = 0;
    int first = 0;
	while(1)
	{
		// 获取坐标
		
		ts_press(&coor, ts);
		printf("(%d, %d)\n", coor.x, coor.y);
		
		if(coor.y>0 && coor.y<100 && coor.x>750 && coor.x<800) //退出
        {
            kill_madplay();
            break;
        }
		else if (coor.y<290 && coor.y>190 && coor.x>350 && coor.x<550 && status_mus == 1 && first == 0)
        {
            first++;
            start_madplay(music_file[index]);
            status_mus = 0;
        }
        
		else if(coor.x>100 && coor.x<300 && coor.y>190 && coor.y<290)
        {
            printf("上一个音乐\n");
            kill_madplay();
            index = (--index == -1) ? count-1 : index;
            start_madplay(music_file[index]);
        }
			
		else if(coor.x>600 && coor.x<800 && coor.y>190 && coor.y<290)
        {
            printf("下一个音乐\n");
            kill_madplay();
            index = (++index == count) ? 0 : index;
            start_madplay(music_file[index]);
        }
			
		else if (coor.y<290 && coor.y>190 && coor.x>350 && coor.x<500 && status_mus == 0)
        {
                printf("停止播放\n");
                stop_madplay();
                status_mus = 1;
        }
        else if (coor.y<290 && coor.y>190 && coor.x>350 && coor.x<550 && status_mus == 1)
        {
                printf("开始播放\n"); 
                continue_madplay();
                status_mus = 0;
        }
        
	}
    free(music_file);
} 